package com.woniu.yoga_zuul.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;

import com.woniu.yoga_zuul.until.JWTHelper;
import org.apache.commons.lang.time.DateUtils;
import org.example.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Map;

@Component
public class GrantFilter extends ZuulFilter {
    @Autowired
    private ObjectMapper objectMapper;
    @Override
    public String filterType() {
        return FilterConstants.POST_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.SEND_RESPONSE_FILTER_ORDER-1;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        String requestURI = request.getRequestURI();
        String login=requestURI.split("/")[2];

        return "login".equals(login);
    }

    @Override
    public Object run() throws ZuulException {


        System.out.println("开始放入tabke");
        RequestContext currentContext = RequestContext.getCurrentContext();
        InputStream responseDataStream = currentContext.getResponseDataStream();
        HttpServletRequest request = currentContext.getRequest();
        String requestURI = request.getRequestURI();
        System.out.println(requestURI);
        if(requestURI.equals("/user-coach/login/loginByPassword") || requestURI.equals("/user-coach/login/loginByTelCode")){
            System.out.println("开始设置密码");
            try {
                String copy = StreamUtils.copyToString(responseDataStream, StandardCharsets.UTF_8);
                Result result = objectMapper.readValue(copy, Result.class);
                if (result.isSuccess() == true) {
                    Map<String, Object> data = (Map<String, Object>) result.getData();
                    Date exp = DateUtils.addDays(new Date(), 7);
                    String jwt = JWTHelper.createJWT(exp, data);
                    data.put("token", jwt);
                    String s = objectMapper.writeValueAsString(result);
                    currentContext.setResponseBody(s);
                } else {
                    String s = objectMapper.writeValueAsString(result);
                    currentContext.setResponseBody(s);
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
